<script setup lang="ts">
import {useUserStore} from '@/stores/user'
import {ElMessageBox, ElMessage} from 'element-plus'
import axios from "axios";
import {Upload,Edit} from "@element-plus/icons-vue";
import {ref, watchEffect} from "vue";
import type {UploadProps} from "element-plus";
const token = ref<string>(window.localStorage.getItem('token') || '')
const btnMessage = ref('修改信息')
const userStore = useUserStore()
const type = ref('')
const localUserInfo = ref({...userStore.userInfo})
// 双向同步
watchEffect(() => {
  localUserInfo.value = {...userStore.userInfo}
})
/**
 * 登录状态 控制登录按钮 和 个人中心
 */

/**
 * 退出登录
 *
 */
const handleClose = () => {
  userStore.userInfoBoxState = false
}
const logout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    try {
      await axios.post('/api/user/logout')
    } catch (e) {
      // 静默处理API错误
    } finally {
      // 确保执行退出操作
      userStore.userInfo = null
      userStore.authState = false
      window.localStorage.removeItem('token')
      userStore.userInfoBoxState = false
      ElMessage.success('已安全退出')
    }
  } catch (cancelError) {
    // 用户取消操作不处理
  }
}
const originalData = ref({}) // 新增原始数据存储
const modifyInfo = async() => {
  if (btnMessage.value === '修改信息') {
    // 进入编辑模式时保存原始数据
    originalData.value = JSON.parse(JSON.stringify(localUserInfo.value))
    btnMessage.value = '保存'
    type.value = 'primary'
  } else {
    try {
      // 比较当前数据与原始数据
      const hasChanges = JSON.stringify(localUserInfo.value) !== JSON.stringify(originalData.value)
      if (!hasChanges) {
        ElMessage.warning('未检测到信息修改')
        btnMessage.value = '修改信息'
        type.value = ''
        return
      }
      const response = await axios.post('/api/user/update', localUserInfo.value, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      if (response.data.code === 200) {
        ElMessage.success('信息更新成功')
        userStore.userInfo = localUserInfo.value // 更新store中的用户信息
        btnMessage.value = '修改信息'
        type.value = ''
      } else {
        ElMessage.error('更新失败：' + response.data.message)
      }
    } catch (error) {
      ElMessage.error('网络请求异常')
      console.error('API调用失败:', error)
    }
  }
}
// 添加头像上传相关逻辑
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  if(response.code === 200) {
    ElMessage.success('头像上传成功')
    // 添加时间戳强制刷新缓存
    localUserInfo.value.avatarUrl = `${response.data}?t=${Date.now()}`
    userStore.userInfo = {...localUserInfo.value}

    // 强制重新加载用户信息
    userStore.fetchUserInfo().then(() => {
      localUserInfo.value = {...userStore.userInfo}
    })
  }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!['image/jpeg', 'image/png', 'image/gif'].includes(rawFile.type)) {
    ElMessage.error('头像必须是JPG/PNG/Gif格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像大小不能超过2MB!')
    return false
  }
  return true
}
</script>

<template>
  <el-dialog
      v-model="userStore.userInfoBoxState"
      title="个人信息"
      width="500"
      :before-close="handleClose"
  >
    <template #default>
      <!--      修改用户信息 待完成-->
      <el-form>
        <div class="avatar">
          <el-form-item label="用户头像：">
            <el-avatar :size="64" :src="localUserInfo.avatarUrl" />
            <el-upload
                class="avatar-uploader"
                action="/api/user/updateAvatar"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="{ 'Authorization': `Bearer ${token}` }"
                :disabled="btnMessage === '修改信息'"
            >
              <el-button
                  type="primary"
                  size="small"
                  style="margin-left: 10px"
                  :disabled="btnMessage === '修改信息'"
              >
                <el-icon><Upload /></el-icon>上传头像
              </el-button>
            </el-upload>
          </el-form-item>
        </div>
        <div class="user-info">
          <el-form-item label="用户账号：">
            {{ localUserInfo.userAccount   }}
          </el-form-item>
          <el-form-item label="用户角色：">
            {{ localUserInfo.userRole == '1' ? '管理员' : '普通用户' }}
          </el-form-item>
          <el-form-item label="用户名：">
            <el-input
                :disabled="btnMessage === '修改信息'"
                v-model="localUserInfo.username"
            >
            </el-input>
          </el-form-item>

          <el-form-item label="联系电话：">
            <el-input
                :disabled="btnMessage === '修改信息'"
                v-model="localUserInfo.phone"
            >
            </el-input>

          </el-form-item>
        </div>
      </el-form>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="modifyInfo" :type><el-icon><Edit /></el-icon>{{ btnMessage }}</el-button>
        <el-button type="danger" @click="logout">
          退出登录
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.avatar-uploader .el-button[disabled] {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
  cursor: not-allowed;
}
.avatar-uploader {
  display: inline-block;
  margin-left: 20px;
}

.avatar {
  width: 100%;
  :deep(.el-form) {
    width: 500px;  /* 限制表单宽度 */
    margin: 0 auto;
  }

  :deep(.el-form-item__label) {
    width: 100px !important;  /* 固定标签宽度 */
    text-align: left !important;  /* 强制左对齐 */
    padding-right: 12px;
    display: inline-block;  /* 确保宽度生效 */

  }

  /* 保持标签对齐 */
  .el-form-item {
    display: flex;
    align-items: center;
  }
}
.user-info {
  width: 100%;
  /* 自动宽度方案 */
  :deep(.el-form) {
    width: 500px;  /* 限制表单宽度 */
    margin: 0 auto;
  }

  :deep(.el-form-item__label) {
    width: 100px !important;  /* 固定标签宽度 */
    text-align: left !important;  /* 强制左对齐 */
    padding-right: 12px;
    display: inline-block;  /* 确保宽度生效 */

  }

  /* 保持标签对齐 */
  .el-form-item {
    display: flex;
    align-items: center;
  }
}
</style>